<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/11
 * Time: 14:53
 */
namespace app\service;
use think\Config;
class KamYellow{
    /**
     * 计算参数签名
     * $params 请求参数
     * $secretKey secretKey
     */
    function gen_signature($secretKey, $params){
        ksort($params);
        $buff="";
        foreach($params as $key=>$value){
            if($value !== null) {
                $buff .=$key;
                $buff .=$value;
            }
        }
        $buff .= $secretKey;
        return md5($buff);
    }

    /**
     * 将输入数据的编码统一转换成utf8
     * @params 输入的参数
     */
    function toUtf8($params){
        $utf8s = array();
        foreach ($params as $key => $value) {
            $utf8s[$key] = is_string($value) ? mb_convert_encoding($value, "utf8", Config::get('kamYellow.internal_string_charset')) : $value;
        }
        return $utf8s;
    }

    /**
     * 反垃圾请求接口简单封装
     * $params 请求参数
     */
    function check($params){
        $params["secretId"] = Config::get('kamYellow.secret_id');
        $params["businessId"] = Config::get('kamYellow.business_id');
        $params["version"] = Config::get('kamYellow.version');
        $params["timestamp"] = sprintf("%d", round(microtime(true)*1000));
        $params["nonce"] = sprintf("%d", rand()); // random int
        $params = $this->toUtf8($params);
        $params["signature"] = $this->gen_signature(Config::get('kamYellow.secret_key'), $params);
        $options = array(
            "http" => array(
                "header"  => "Content-type: application/x-www-form-urlencoded\r\n",
                "method"  => "POST",
                "timeout" => Config::get('kamYellow.api_timeout'), // read timeout in seconds
                "content" => http_build_query($params),
            ),
        );
        $context  = stream_context_create($options);
        $result = file_get_contents(Config::get('kamYellow.api_url'), false, $context);
        if($result === FALSE){
            throw new \LogicException('file_get_contents failed',500);
        }else{
            return json_decode($result, true);
        }
    }

    function main($image_path){
        $images = array();
        array_push($images, array(// type=1表示传图片url检查
            "name" => $image_path,
            "type" => 1,
            "data" => $image_path,
        ));
        $params = array(
            "images"=>json_encode($images),
            "account"=>"php@163.com",
            "ip"=>"123.115.77.137"
        );
        $ret = $this->check($params);
        if ($ret["code"] == 200) {
            $result = $ret["result"];
            //此时返回每张图片的鉴黄结果
            $image_arr['name'] = $image_path;
            $image_arr['labels'] = $result[0]['labels'];
        }
        return $image_arr;
    }

}